<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: RepayCountController.php
 * +----------------------------------------------------------------------
 * | Author: lijiafei
 * +----------------------------------------------------------------------
 * | Description:
 * +----------------------------------------------------------------------
 * | Others: 其他内容的说明
 * +----------------------------------------------------------------------
 * | History:
 * +----------------------------------------------------------------------
 * | 1.Date: 2019/2/28 Author: lijiafei Modification: 创建
 * +----------------------------------------------------------------------
 */

namespace App\Http\Controllers\Backend\Repay;


use App\Library\Tools\ExcelExport;
use App\Models\LoanApply;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\Traits\Repay;
use App\Models\User;
use App\Models\UserLoanRequest;
use Illuminate\Support\Carbon;

class RepayCountController
{
    /**
     * Description:逾期表
     * Author:lijiafei
     */
    public function overdueExcel(){
        //查找当前逾期的没有还的记录
        $repaySummaryInfo = RepaySummary::with(['recordOne'=>function($q){
            $q->where('status','<>',RepayRecord::STATUS_FOUR);
            $q->where('pay_off',RepayRecord::PAY_OFF_ONE);
            $q->whereDate('normal_date','<',Carbon::now()->toDateString());
        }])
            ->where('repay_summaries.current_repay',RepaySummary::CURRENT_REPAY_ONE)
            ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
            ->get();
        $excelData = array();
        if(!empty($repaySummaryInfo)){
            foreach ($repaySummaryInfo as $k => $value){
                if($value->recordOne){
                    $arrayData = array();
                    $arrayData['record_id'] = $value->recordOne->id;
                    $arrayData['product'] = '快闪卡贷';//产品
                    $userInfo = $this->getUserInfo($value->recordOne->uid);
                    $arrayData['user_id'] = $userInfo->nfsp_user_id;//用户号
                    $arrayData['name'] = $userInfo->name;//用户姓名
                    $arrayData['source_code'] = $userInfo->source;//渠道号
                    $arrayData['source_name'] = '';//渠道来源
                    $arrayData['loan_id'] = $value->loan_id;//放款交易号
                    $channel_name = $this->getChannelName($value->loan_request_id);
                    $arrayData['channel_name'] = $channel_name;//放款资方渠道
                    $arrayData['amount'] = $value->amount;//放款金额
                    $arrayData['period_count'] = $value->period_count;//分期期数
                    $arrayData['status'] = '逾期';//还款状态
                    $arrayData['period'] = $value->period;//当前期数
                    $arrayData['normal_date'] = $value->recordOne->normal_date;//预计还款日期
                    $moneyInfo = RepaySummary::getRepayMoney($value->recordOne);
                    $arrayData['all_money'] = $moneyInfo['all_money'];//应收总金额
                    $arrayData['ys_amount'] = $moneyInfo['amount'];//应收本金
                    $arrayData['lending_money'] = $moneyInfo['lending_money'];//应收利息
                    $arrayData['manage_money'] = $moneyInfo['manage_money'];//应收贷后管理费
                    $arrayData['month_money'] = $moneyInfo['month_money'];//应收其他费用(月报费)
                    $arrayData['money_repayment_money'] = $moneyInfo['money_repayment_money'];//资方提前结清手续费
                    $arrayData['common_repayment_money'] = $moneyInfo['common_repayment_money'];//平台提前结清手续费
                    $arrayData['money_fines_money'] = $moneyInfo['money_fines_money'];//资方罚息
                    $arrayData['common_fines_money'] = $moneyInfo['common_fines_money'];//平台罚息
                    $arrayData['failure'] = $value->recordOne->money->failure;//失败原因
                    $arrayData['current_period'] = $value->period;//当前逾期是第几期
                    $arrayData['overdue_day'] = count_days(Carbon::now()->toDateString(),$value->recordOne->normal_date);//逾期天数
                    $arrayData['repay_type'] = $this->getRepayType($value->recordOne->money->type);//还款类型
                    $arrayData['current_date'] = Carbon::now()->toDateString();//对账日期
                    $arrayData['amount_lending_money'] = $arrayData['amount'] + $arrayData['lending_money'];//本息和
                    $yihuanMoney = RepaySummary::getYihuanMoney($value->recordOne);
                    $arrayData['yh_all_money'] = $yihuanMoney['all_money'] + $yihuanMoney['money_repayment_money'] + $yihuanMoney['common_repayment_money'];//已还总金额
                    $arrayData['yh_amount'] = $yihuanMoney['amount'];//已还本金
                    $arrayData['yh_lending_money'] = $yihuanMoney['lending_money'];//已还利息
                    $arrayData['yh_manage_money'] = $yihuanMoney['manage_money'];//已还贷后管理费
                    $arrayData['yh_money_fines_money'] = $yihuanMoney['money_fines_money'];//已还资方罚息
                    $arrayData['yh_common_fines_money'] = $yihuanMoney['common_fines_money'];//已还平台罚息
                    $arrayData['yh_month_money'] = $yihuanMoney['month_money'];//已还其他费用(月保费)
                    $arrayData['yh_money_repayment_money'] = $yihuanMoney['money_repayment_money'];//已还资方提前结清
                    $arrayData['yh_common_repayment_money'] = $yihuanMoney['common_repayment_money'];//已还公共提前结清
                    $excelData[] = $arrayData;
                }
            }
        }
        $header = ['产品','用户号','用户姓名','渠道号','渠道来源','放款交易号','放款资方渠道','放款金额','分期期数','还款状态','当前期数','预计还款日期','应收总金额','应收本金','应收利息','应收贷后管理费','应收其他费用(月报费)','资方提前结清手续费','平台提前结清手续费','资方罚息','平台罚息','失败原因','当前逾期期数','当前逾期天数','还款类型','对账日期','本息和','已还款总金额','已还本金','已还利息','已还贷后管理费','已还资方罚息','已还公共罚息','已还其他费用(月保费)','已还资方提前结清手续费','已还平台提前结清手续费'];
        $fields = ['product','user_id','name','source_code','source_name','loan_id','channel_name','amount','period_count','status','period','normal_date','all_money','ys_amount','lending_money','manage_money','month_money','money_repayment_money','common_repayment_money','money_fines_money','common_fines_money','failure','current_period','overdue_day','repay_type','current_date','amount_lending_money','yh_all_money','yh_amount','yh_lending_money','yh_manage_money','yh_money_fines_money','yh_common_fines_money','yh_month_money','yh_money_repayment_money','yh_common_repayment_money'];
        $info = new ExcelExport($excelData,$header,$fields,'overdueExcel.xlsx');
        $info->export();

    }

    /**
     * Description:还款表
     * Author:lijiafei
     */
    public function repayExcel(){
        //查询昨天的还款成功记录
        $info = RepayRecord::where(function ($q){
            $q->where('status',RepayRecord::STATUS_FOUR)->where('pay_off',RepayRecord::PAY_OFF_ONE)->whereDate('repay_date',Carbon::yesterday()->toDateString());
        })->orWhere(function($q){
            $q->where('period',0)->where('status',RepayRecord::STATUS_FOUR)->where('pay_off',RepayRecord::PAY_OFF_TWO)->whereDate('repay_date',Carbon::yesterday()->toDateString());
        })->get();
        $excelData = array();
        if(!empty($info)){
            foreach ($info as $k => $value){
                $summaryInfo = RepaySummary::select('loan_id','loan_request_id','amount','period_count')->find($value->summary_id);
                $loanApply = LoanApply::select('out_trade_id')->find($summaryInfo->loan_request_id);
                $arrayData = array();
                $arrayData['record_id'] = $value->id;
                $arrayData['product'] = '快闪卡贷';//产品
                $userInfo = $this->getUserInfo($value->uid);
                $arrayData['user_id'] = $userInfo->nfsp_user_id;//用户号
                $arrayData['name'] = $userInfo->name;//用户姓名
                $arrayData['phone_num'] = $userInfo->phone_num;//手机号
                $arrayData['cert_number'] = $userInfo->cert_no;//身份证号
                $arrayData['loan_order_id'] = $loanApply->out_trade_id;//借款订单号
                $arrayData['source_code'] = $userInfo->source;//渠道号
                $arrayData['source_name'] = '';//渠道来源
                $arrayData['loan_id'] = $summaryInfo->loan_id;//放款交易号
                $channel_name = $this->getChannelName($summaryInfo->loan_request_id);
                $arrayData['channel_name'] = $channel_name;//放款资方渠道
                $arrayData['amount'] = $summaryInfo->amount;//放款金额
                $arrayData['period_count'] = $summaryInfo->period_count;//分期期数
                $historyMoney = $this->getHistoryMoney($value,$summaryInfo);//获取历史各种金额
                $arrayData['history_all_money'] = $historyMoney['history_all_money'];//历史总金额
                $arrayData['history_amount'] = $historyMoney['history_amount'];//历史总本金
                $arrayData['history_lending_money'] = $historyMoney['history_lending_money'];//历史总利息
                $arrayData['history_manage_money'] = $historyMoney['history_manage_money'];//历史总贷后管理费
                $arrayData['history_money_fines_money'] = $historyMoney['history_money_fines_money'];//历史总资方罚息
                $arrayData['history_common_fines_money'] = $historyMoney['history_common_fines_money'];//历史总平台罚息
                $arrayData['history_other_money'] = $historyMoney['history_other_money'];//历史总其他金额
                $arrayData['trade_number'] = $value->common->trade_no;//还款交易号
                $arrayData['channel'] = '京东签约';
                $arrayData['repay_type'] = $this->getRepayType($value->money->type);
                $arrayData['current_period'] = $value->period;
                $arrayData['normal_date'] = $value->normal_date;
                $arrayData['repay_date'] = $value->repay_date;
                $yihuanMoney = RepaySummary::getYihuanMoney($value);
                $arrayData['yh_all_money'] = $yihuanMoney['all_money'] + $yihuanMoney['money_repayment_money'] + $yihuanMoney['common_repayment_money'];//已还总金额
                $arrayData['yh_amount'] = $yihuanMoney['amount'];//已还本金
                $arrayData['yh_lending_money'] = $yihuanMoney['lending_money'];//已还利息
                $arrayData['yh_manage_money'] = $yihuanMoney['manage_money'];//已还贷后管理费
                $arrayData['yh_money_fines_money'] = $yihuanMoney['money_fines_money'];//已还资方罚息
                $arrayData['yh_common_fines_money'] = $yihuanMoney['common_fines_money'];//已还平台罚息
                $arrayData['yh_month_money'] = $yihuanMoney['month_money'];//已还其他费用(月保费)
                $arrayData['yh_money_repayment_money'] = $yihuanMoney['money_repayment_money'];//已还资方提前结清
                $arrayData['yh_common_repayment_money'] = $yihuanMoney['common_repayment_money'];//已还公共提前结清
                $excelData[] = $arrayData;
            }
        }
        $header = ['产品','用户号','用户姓名','手机号','身份证号','借款订单号','渠道号','渠道来源','放款交易号','放款资方渠道','放款金额','分期期数','实收历史总金额','实收历史总本金','实收历史总利息','历史平台总服务费','历史总资方罚息','历史总平台罚息','历史总其他金额','还款交易号','还款渠道方','还款方式','还款第几期','预计还款日期','实际还款日期','实还款总金额','实还本金','实还利息','实还贷后管理费','实还资方罚息','实还公共罚息','实还其他费用(月保费)','实还资方提前结清手续费','实还平台提前结清手续费'];
        $fields = ['product','user_id','name','phone_num','cert_number','loan_order_id','source_code','source_name','loan_id','channel_name','amount','period_count','history_all_money','history_amount','history_lending_money','history_manage_money','history_money_fines_money','history_common_fines_money','history_other_money','trade_number','channel','repay_type','current_period','normal_date','repay_date','yh_all_money','yh_amount','yh_lending_money','yh_manage_money','yh_money_fines_money','yh_common_fines_money','yh_month_money','yh_money_repayment_money','yh_common_repayment_money'];
        $info = new ExcelExport($excelData,$header,$fields,'repayExcel.xlsx');
        $info->export();

    }

    /**
     * Description:获取用户信息
     * Author:lijiafei
     * @param $user_id int
     * @return User
     */
    protected function getUserInfo($user_id){
        $info = User::select('nfsp_user_id','source','phone_num')->where('id',$user_id)->first();
        $info->name = $info->real_name;
        $info->cert_number = $info->cert_no;
        return $info;
    }

    /**
     * Description:获取放款资方渠道名称
     * Author:lijiafei
     * @param $loan_request_id int user_loan_request表的id
     * @return mixed string 资方名称
     */
    protected function getChannelName($loan_request_id){
        $requestInfo = UserLoanRequest::select('channel')->find($loan_request_id);
        $channel_name = '';
        if(!empty($requestInfo->channel)){
            $channel_name = SettingChannel::getChannelNameByChannel($requestInfo->channel);
        }
        return $channel_name;
    }



    protected function getRepayType($type){
//        成功详细状态 0:全部还清, 1:NN 待还,2:NR 正常还款,3:NT 当期提前还款,4:NJ 提前结清,5:ON 逾期,6:OR 逾期还款,7:DN 代偿,8:DR 代偿还款,9:DD 代偿期代偿,10:ND 正常期代偿,11:OD 逾期代偿',
        $msg = '';
        switch ($type){
            case 0:
                $msg = '全部还清';
                break;
            case 1:
                $msg = '待还';
                break;
            case 2:
                $msg = '正常还款';
                break;
            case 3:
                $msg = '当前提前还款';
                break;
            case 4:
                $msg = '提前结清';
                break;
            case 5:
                $msg = '逾期';
                break;
            case 6:
                $msg = '逾期还款';
                break;
            case 7:
                $msg = '代偿';
                break;
            case 8:
                $msg = '代偿还款';
                break;
            case 9:
                $msg = '代偿期代偿';
                break;
            case 10:
                $msg = '正常期代偿';
                break;
            case 11:
                $msg = '逾期代偿';
                break;
            default:
                return '';
        }
        return $msg;
    }

    /**
     * Description:算出来历史总金额
     * Author:lijiafei
     * @param RepaySummary $summaryInfo
     * @return array
     */
    protected function getHistoryMoney(RepayRecord $recordInfo,RepaySummary $summaryInfo){
        //查找历史的已经还清的
        $period = $recordInfo->period;
        $history_all_money = 0;//历史总金额
        $history_amount = 0;//历史总本金
        $history_lending_money = 0;//历史总利息
        $history_manage_money = 0;//贷后管理费
        $history_other_money = 0;//其他费用 月保费
        $history_money_fines_money = 0;//历史资方罚息
        $history_common_fines_money = 0;//历史平台罚息
        foreach (RepayRecord::where('summary_id',$recordInfo->summary_id)
                     ->where('period',"<>",0)
                     ->where('pay_off',RepayRecord::PAY_OFF_ONE)
                     ->where('status',RepayRecord::STATUS_FOUR)
                     ->cursor() as $k => $value){
            $money = RepaySummary::getYihuanMoney($value);
            $history_all_money += $money['all_money'];//总金额
            $history_amount += $money['amount'];
            $history_lending_money += $money['lending_money'];
            $history_manage_money += $money['manage_money'];
            $history_other_money += $money['month_money'];
            $history_money_fines_money += $money['money_fines_money'];
            $history_common_fines_money += $money['common_fines_money'];

        }
        if(0 == $period){
            //当前这条记录是全部结清
            $money = RepaySummary::getYihuanMoney($recordInfo);
            $history_all_money += $money['all_money'];//总金额
            $history_amount += $money['amount'];
            $history_lending_money += $money['lending_money'];
            $history_manage_money += $money['manage_money'];
            $history_other_money += $money['month_money'];
            $history_money_fines_money += $money['money_fines_money'];
            $history_common_fines_money += $money['common_fines_money'];
        }
        $return = [
            'history_all_money' => $history_all_money,
            'history_amount' => $history_amount,
            'history_lending_money' => $history_lending_money,
            'history_manage_money' => $history_manage_money,
            'history_other_money' => $history_other_money,
            'history_money_fines_money' => $history_money_fines_money,
            'history_common_fines_money' => $history_common_fines_money,

        ];
        return $return;
    }
















}